<?php

class Profile_IndexController extends Controller_Site_Profile 
{
	public function indexAction()
	{
		
	}
	
	public function changeInfoAction()
	{
		$this->_ajaxOnly();
		$params = $this->_getAllParams();
		$input = ValidationService::getInstance()->getRegistrationInputFilterChain();
		
		$input->setData($params);
		if (!$input->isValid()) {
			$messages = $input->getMessages();
			$this->_setJson(array("success" => false, "errors" => $messages)); 
			return;
		}
		
		
		
		if (isset($_FILES['avatar'])) {
			$photoId = $this->_uploadAvatar();
			$params['file_id'] = $photoId;
		}
		$this->getProfileService()->saveProfileFields($this->profile->getId(), $params);
	}
	
	public function addPhotoAction()
	{
		
	}
	
	public function addVideoAction()
	{
		
	}
	
	public function addPostAction()
	{
		
	}
	
	private function _uploadAvatar()
	{
		$date = date('Y-m-d H:i:s');
		if (isset($_FILES['avatar'])) {
			$extension = strtolower(array_pop(explode('.', $image["name"])));
			
			$size = $image['size'];
			
			try {
				$content = file_get_contents($image['tmp_name']);
			} catch (Exception_File $e) {}
			$url =  '/' . md5(time()) . '.' . $extension;
			$path = BASE_DIR . '/htdocs/images/avatar' . $url;
			
			try {
				file_put_contents($path, $content);
				$size = getimagesize($path);
			} catch (Exception_File $e) {}
			
			// creating new file row
			$fileRow = FilePeer::getInstance()->createRow();
			$fileRow->setHash(md5($url));
			$fileRow->setUri($url);
			$fileRow->setSize($size);
			$fileRow->setCreated($date);
			$fileRow->setExt($extension);
			$fileRow->save();
			
			$fileId = $fileRow->getId();
			return $fileId;
		}
		return null;
	}
}